package cn.fl.institution.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.project.constant.PrjBscInfoConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.institution.condition.InstitutionEarningsQueryCondition;
import cn.fl.institution.service.IInstitutionEarningsService;
import cn.fl.institution.vo.InstitutionEarningsVO;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.vo.PrjBscInfoVO;

@Controller
@RequestMapping("/institution/earnings")
public class InstitutionEarningsController {
	
	private static final Logger logger = LoggerFactory.getLogger(InstitutionEarningsController.class);
	
	@Autowired
	private IInstitutionEarningsService institutionEarningsService;

    @Autowired
    private IPrjBscInfoService prjBscInfoService; // 项目基础信息表
    
	/**
	 * 到列表页面
	 * @param request
	 * @param response
	 * @return
	 */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
    	 BaseLogUtils.info(logger, "toListPage", "加载资管收益列表页面.", CurrentThreadContext.getCurrentUserName());
         ModelAndView mav = new ModelAndView("institution/earnings/institutionEarningsList");
         return mav;
	}
    
    /**
     * 初始化列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        InstitutionEarningsQueryCondition qc = new InstitutionEarningsQueryCondition();
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm.trim());
        }
        String lsCntNo = request.getParameter("lsCntNo");
        if (StringUtils.isNotEmpty(lsCntNo)) {
            qc.setLsCntNo(lsCntNo.trim());
        }
        String fundRasInsNm = request.getParameter("fundRasInsNm");
        if (StringUtils.isNotEmpty(fundRasInsNm)) {
            qc.setInsNm(fundRasInsNm.trim());
        }
        String startPayDt = request.getParameter("startPayDt");
        if (StringUtils.isNotEmpty(startPayDt)) {
            qc.setStartPayDt(DateUtils.formatStringToDate(startPayDt.trim(), "yyyy-MM-dd"));
        }
        String endPayDt = request.getParameter("endPayDt");
        if (StringUtils.isNotEmpty(endPayDt)) {
            qc.setEndPayDt(DateUtils.formatStringToDate(endPayDt.trim(), "yyyy-MM-dd"));
        }
        String startLastPayDt = request.getParameter("startLastPayDt");
        if (StringUtils.isNotEmpty(startLastPayDt)) {
            qc.setStartLastPayDt(DateUtils.formatStringToDate(startLastPayDt.trim(), "yyyy-MM-dd"));
        }
        String endLastPayDt = request.getParameter("endLastPayDt");
        if (StringUtils.isNotEmpty(endLastPayDt)) {
            qc.setEndLastPayDt(DateUtils.formatStringToDate(endLastPayDt.trim(), "yyyy-MM-dd"));
        }
        //REQ-2106 资金管理—资管收益添加查询条件 by zhangkai 20190115
        //数据过滤：浙银收益列表数据，增加资方已放款条件(增加默认查询条件)
        //需求要求 irr 前不包含 后包含
        String startIrrPct = request.getParameter("startIrrPct");
        if (StringUtils.isNotEmpty(startIrrPct)) {
            qc.setStartIrrPct(Double.valueOf(startIrrPct.trim()));
        }
        String endIrrPct = request.getParameter("endIrrPct");
        if (StringUtils.isNotEmpty(endIrrPct)) {
            qc.setEndIrrPct(Double.valueOf(endIrrPct.trim()));
        }
        String isOverdue = request.getParameter("isOverdue");
        if (StringUtils.isNotEmpty(isOverdue)) {
        	qc.setIsOverdue(Integer.valueOf(isOverdue.trim()));
        }
        
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initList", "资管收益列表 初始化列表.PAGE:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        try {
	        Pager pager = this.institutionEarningsService.searchListPage(page);
	        @SuppressWarnings("unchecked")
			List<InstitutionEarningsVO> list = (List<InstitutionEarningsVO>) pager.getResultList();
	        ListPageVO<InstitutionEarningsVO> listPage = new ListPageVO<InstitutionEarningsVO>(list, pager.getTotalCount());
	        BaseLogUtils.info(logger, "initList", "资管收益列表 初始化列表.DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
	        return listPage;
        }
        catch(Exception ex) {
        	ex.printStackTrace();
        }
        return null;
    }

    /**
     * 资管收益到详情页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toDetailPage", "加载资管收益详情页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("institution/earnings/institutionEarningsDetail");
		String lsCntNo = request.getParameter("lsCntNo");
		request.setAttribute("lsCntNo", lsCntNo);
		return mav;
    }

    /**
     * 资管收益详情.项目基本信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loadPrjBscInfo.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object loadPrjBscInfo(HttpServletRequest request, HttpServletResponse response) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "资管收益详情.项目基本信息");
        String lsCntNo = request.getParameter("lsCntNo");
        if(StringUtils.isEmpty(lsCntNo)) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("合同号不能为空！");
    		return result;
        }
        Map<String, Object> data = new HashMap<String, Object>();
        PrjBscInfoQueryCondition prjBscQC = new PrjBscInfoQueryCondition();
        prjBscQC.setLsCntNo(lsCntNo);
		List<PrjBscInfoVO> prjBscInfoList = this.prjBscInfoService.searchPrjBscInfoList(prjBscQC);
		PrjBscInfoVO prjBscInfo = null;
		if(CollectionUtils.isNotEmpty(prjBscInfoList)) {
			prjBscInfo = prjBscInfoList.get(0);
		}
		else {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("未找到合同号为“"+lsCntNo+"”的项目基本信息！");
    		return result;
		}
		BaseLogUtils.info(logger, "loadPrjBscInfo", "资管收益详情.项目基本信息:" + JSONObject.toJSONString(prjBscInfo), CurrentThreadContext.getCurrentUserName());       
		data.put("prjBscInfo", prjBscInfo);
		result.setData(data);
		return prjBscInfo;
    }
    
    /**
     * 资管收益详情列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/initDetail.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initDetail(HttpServletRequest request, HttpServletResponse response) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "资管收益详情");
        String lsCntNo = request.getParameter("lsCntNo");
        if(StringUtils.isEmpty(lsCntNo)) {
    		result.setSuccess(BaseConstant.IS_YESNO_NO);
    		result.setInfo("合同号不能为空！");
    		return result;
        }
        BaseLogUtils.info(logger, "initDetail", "资管收益详情 lsCntNo:" + lsCntNo, CurrentThreadContext.getCurrentUserName());
        
		InstitutionEarningsQueryCondition ieQC = new InstitutionEarningsQueryCondition();
        ieQC.setLsCntNo(lsCntNo);
        List<InstitutionEarningsVO> list = this.institutionEarningsService.searchDetail(ieQC);
        BaseLogUtils.info(logger, "initDetail", "资管收益详情 DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());        
        result.setData(list);
        return result;
    }
    
    
    /**
     * 资管收益详情列表合计
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/sumDtl.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object sumDtl(HttpServletRequest request, HttpServletResponse response) {
    	Map<String,Double> result = new HashMap<>();
    	Double sumEarAmt = 0.0;
    	Double sumPaidUpAmt = 0.0;
    	String lsCntNo = request.getParameter("lsCntNo");
    	if(StringUtils.isEmpty(lsCntNo)) {
    		return result;
    	}
    	BaseLogUtils.info(logger, "initDetail", "资管收益详情合计 lsCntNo:" + lsCntNo, CurrentThreadContext.getCurrentUserName());
    	
    	InstitutionEarningsQueryCondition ieQC = new InstitutionEarningsQueryCondition();
    	ieQC.setLsCntNo(lsCntNo);
    	List<InstitutionEarningsVO> list = this.institutionEarningsService.searchDetail(ieQC);
    	
    	for (InstitutionEarningsVO it : list) {
    		sumEarAmt += it.getEarAmt();
    		sumPaidUpAmt += it.getPaidUpAmt();
    		if(PrjBscInfoConstant.PRJ_INS_CODE_ZBBANKX.equals(it.getInsCode())){
                sumEarAmt += it.getVouchAmt() ;
                sumPaidUpAmt += it.getPaidVouchAmt() ;
            }
		}
    	result.put("SUMEARAMT", sumEarAmt);
    	result.put("SUMPAIDUPAMT", sumPaidUpAmt);
    	BaseLogUtils.info(logger, "initDetail", "资管收益详情合计 DATA:" + JSONObject.toJSONString(result), CurrentThreadContext.getCurrentUserName());        
    	return result;
    }
    
    /**
     * 资管收益详情列表合计
     * @param request
     * @param responses
     * @return
     */
    @RequestMapping(value = "/sumIte.do", method = {RequestMethod.GET})
    @ResponseBody
    public Map<String, String> sumIte(HttpServletRequest request, HttpServletResponse response) {
    	InstitutionEarningsQueryCondition qc = new InstitutionEarningsQueryCondition();
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm.trim());
        }
        String lsCntNo = request.getParameter("lsCntNo");
        if (StringUtils.isNotEmpty(lsCntNo)) {
            qc.setLsCntNo(lsCntNo.trim());
        }
        String fundRasInsNm = request.getParameter("fundRasInsNm");
        if (StringUtils.isNotEmpty(fundRasInsNm)) {
            qc.setInsNm(fundRasInsNm.trim());
        }
        String startPayDt = request.getParameter("startPayDt");
        if (StringUtils.isNotEmpty(startPayDt)) {
            qc.setStartPayDt(DateUtils.formatStringToDate(startPayDt.trim(), "yyyy-MM-dd"));
        }
        String endPayDt = request.getParameter("endPayDt");
        if (StringUtils.isNotEmpty(endPayDt)) {
            qc.setEndPayDt(DateUtils.formatStringToDate(endPayDt.trim(), "yyyy-MM-dd"));
        }
        String startLastPayDt = request.getParameter("startLastPayDt");
        if (StringUtils.isNotEmpty(startLastPayDt)) {
            qc.setStartLastPayDt(DateUtils.formatStringToDate(startLastPayDt.trim(), "yyyy-MM-dd"));
        }
        String endLastPayDt = request.getParameter("endLastPayDt");
        if (StringUtils.isNotEmpty(endLastPayDt)) {
            qc.setEndLastPayDt(DateUtils.formatStringToDate(endLastPayDt.trim(), "yyyy-MM-dd"));
        }
        String startIrrPct = request.getParameter("startIrrPct");
        if (StringUtils.isNotEmpty(startIrrPct)) {
            qc.setStartIrrPct(Double.valueOf(startIrrPct.trim()));
        }
        String endIrrPct = request.getParameter("endIrrPct");
        if (StringUtils.isNotEmpty(endIrrPct)) {
            qc.setEndIrrPct(Double.valueOf(endIrrPct.trim()));
        }
        String isOverdue = request.getParameter("isOverdue");
        if (StringUtils.isNotEmpty(isOverdue)) {
        	qc.setIsOverdue(Integer.valueOf(isOverdue.trim()));
        }
        
        BaseLogUtils.info(logger, "initList", "资管收益列表 初始化列表合计.qc:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
    	Map<String, String> result = this.institutionEarningsService.searchListTotal(qc);
        BaseLogUtils.info(logger, "initList", "资管收益列表 初始化列表合计.result:" + JSONObject.toJSONString(result), CurrentThreadContext.getCurrentUserName());
    	return result;
    }
    
}
